<script setup lang="ts">
import { reactive, ref } from 'vue';
import { NButton, NPopconfirm, NSpace, NTag } from 'naive-ui';
import { fetchFillTemplateList, deleteFillTemplate } from '@/service/api';
import { useBoolean, useLoading } from '@/hooks/common';
import { $t } from '@/locales';
import TemplateOperateDrawer from './modules/template-operate-drawer.vue';
import TemplateFormDesigner from './modules/template-form-designer.vue';

const { loading, startLoading, endLoading } = useLoading(false);
const { bool: visible, setTrue: openDrawer, setFalse: closeDrawer } = useBoolean();
const { bool: designerVisible, setTrue: openDesigner, setFalse: closeDesigner } = useBoolean();

const queryParams = reactive<Api.Dataplatform.FillTemplateSearchParams>({
  pageNum: 1,
  pageSize: 10,
  name: '',
  code: '',
  status: undefined,
  projectId: undefined
});

const tableData = ref<Api.Dataplatform.FillTemplate[]>([]);
const total = ref(0);
const operateType = ref<'add' | 'edit'>('add');
const editingData = ref<Api.Dataplatform.FillTemplate | null>(null);
const designingTemplate = ref<Api.Dataplatform.FillTemplate | null>(null);

const columns = [
  { key: 'id', title: 'ID', width: 80 },
  { key: 'name', title: $t('page.dataplatform.fill.templateName'), width: 150 },
  { key: 'code', title: $t('page.dataplatform.fill.templateCode'), width: 150 },
  { key: 'description', title: $t('page.dataplatform.fill.description'), width: 200, ellipsis: { tooltip: true } },
  { key: 'targetTable', title: $t('page.dataplatform.fill.targetTable'), width: 150 },
  {
    key: 'status',
    title: $t('page.dataplatform.common.status'),
    width: 100,
    render: (row: Api.Dataplatform.FillTemplate) => {
      const tagType = row.status === 1 ? 'success' : 'error';
      const text = row.status === 1 ? $t('page.dataplatform.common.enabled') : $t('page.dataplatform.common.disabled');
      return <NTag type={tagType}>{text}</NTag>;
    }
  },
  { key: 'version', title: $t('page.dataplatform.fill.version'), width: 100 },
  { key: 'createTime', title: $t('page.dataplatform.common.createTime'), width: 180 },
  {
    key: 'actions',
    title: $t('page.dataplatform.common.action'),
    width: 280,
    fixed: 'right' as const,
    render: (row: Api.Dataplatform.FillTemplate) => {
      return (
        <NSpace>
          <NButton size="small" onClick={() => handleDesign(row)}>
            {$t('page.dataplatform.fill.designForm')}
          </NButton>
          <NButton size="small" type="primary" onClick={() => handleEdit(row)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton size="small" type="error">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </NSpace>
      );
    }
  }
];

async function getTableData() {
  startLoading();
  const { data, error } = await fetchFillTemplateList(queryParams);
  if (!error) {
    tableData.value = data?.rows || [];
    total.value = data?.total || 0;
  }
  endLoading();
}

function handleQuery() {
  queryParams.pageNum = 1;
  getTableData();
}

function handleReset() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    name: '',
    code: '',
    status: undefined,
    projectId: undefined
  });
  getTableData();
}

function handleAdd() {
  operateType.value = 'add';
  editingData.value = null;
  openDrawer();
}

function handleEdit(row: Api.Dataplatform.FillTemplate) {
  operateType.value = 'edit';
  editingData.value = row;
  openDrawer();
}

function handleDesign(row: Api.Dataplatform.FillTemplate) {
  designingTemplate.value = row;
  openDesigner();
}

async function handleDelete(id: number) {
  const { error } = await deleteFillTemplate([id]);
  if (!error) {
    window.$message?.success($t('common.deleteSuccess'));
    getTableData();
  }
}

function handlePageChange(page: number) {
  queryParams.pageNum = page;
  getTableData();
}

function handlePageSizeChange(pageSize: number) {
  queryParams.pageSize = pageSize;
  queryParams.pageNum = 1;
  getTableData();
}

function handleOperateSuccess() {
  closeDrawer();
  getTableData();
}

function handleDesignSuccess() {
  closeDesigner();
  getTableData();
}

// 初始化
getTableData();
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard :title="$t('page.dataplatform.fill.templateManagement')" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          {{ $t('common.add') }}
        </NButton>
      </template>

      <div class="h-full flex-col">
        <NSpace class="pb-12px" justify="space-between">
          <NSpace>
            <NInput
              v-model:value="queryParams.name"
              :placeholder="$t('page.dataplatform.fill.templateName')"
              clearable
              @keyup.enter="handleQuery"
            />
            <NInput
              v-model:value="queryParams.code"
              :placeholder="$t('page.dataplatform.fill.templateCode')"
              clearable
              @keyup.enter="handleQuery"
            />
            <NSelect
              v-model:value="queryParams.status"
              :placeholder="$t('page.dataplatform.common.status')"
              :options="[
                { label: $t('page.dataplatform.common.enabled'), value: 1 },
                { label: $t('page.dataplatform.common.disabled'), value: 0 }
              ]"
              clearable
              class="w-120px"
            />
          </NSpace>
          <NSpace>
            <NButton @click="handleReset">{{ $t('common.reset') }}</NButton>
            <NButton type="primary" @click="handleQuery">{{ $t('common.search') }}</NButton>
          </NSpace>
        </NSpace>

        <NDataTable
          :columns="columns"
          :data="tableData"
          :loading="loading"
          :scroll-x="1400"
          :pagination="{
            page: queryParams.pageNum,
            pageSize: queryParams.pageSize,
            itemCount: total,
            showSizePicker: true,
            pageSizes: [10, 20, 50, 100],
            onUpdatePage: handlePageChange,
            onUpdatePageSize: handlePageSizeChange
          }"
          class="flex-1-hidden"
        />
      </div>
    </NCard>

    <TemplateOperateDrawer
      v-model:visible="visible"
      :operate-type="operateType"
      :row-data="editingData"
      @success="handleOperateSuccess"
    />

    <TemplateFormDesigner
      v-model:visible="designerVisible"
      :template="designingTemplate"
      @success="handleDesignSuccess"
    />
  </div>
</template>

<style scoped></style>
